import pandas as pd
import numpy as np
from datetime import datetime, timedelta

class StrategyGenerator:
    def __init__(self, config):
        self.config = config
        
    def generate_short_term_strategy(self, stock_code, tech_analysis):
        """生成短期策略（1-5天）"""
        # 根据技术指标分析生成短期策略
        signals = []
        
        # 检查均线指标
        if tech_analysis['MA_5'] > tech_analysis['MA_10'] and tech_analysis['trend'] == 'up':
            signals.append({
                'signal': 'buy',
                'strength': 'strong',
                'reason': 'MA金叉且上升趋势确认',
                'timeframe': 'short'
            })
        
        # 检查RSI指标
        if 30 <= tech_analysis['RSI_6'] <= 40:
            signals.append({
                'signal': 'buy',
                'strength': 'medium',
                'reason': 'RSI处于超卖区域，有反弹可能',
                'timeframe': 'short'
            })
            
        # 检查MACD指标
        if tech_analysis['MACD_hist'] > 0 and tech_analysis['MACD_hist_prev'] < 0:
            signals.append({
                'signal': 'buy',
                'strength': 'strong',
                'reason': 'MACD柱线由负转正，买入信号',
                'timeframe': 'short'
            })
        
        # 生成综合策略建议
        strategy = self._compile_strategy(signals, 'short')
        return strategy
    
    def generate_medium_term_strategy(self, stock_code, tech_analysis, fundamental_analysis):
        """生成中期策略（1-3个月）"""
        signals = []
        
        # 结合技术面和基本面分析
        if tech_analysis['trend'] == 'up' and fundamental_analysis['valuation'] == 'undervalued':
            signals.append({
                'signal': 'buy',
                'strength': 'strong',
                'reason': '技术面趋势向上，且基本面估值偏低',
                'timeframe': 'medium'
            })
        
        # 行业分析
        if fundamental_analysis['industry_outlook'] == 'positive':
            signals.append({
                'signal': 'buy',
                'strength': 'medium',
                'reason': '所在行业前景良好',
                'timeframe': 'medium'
            })
            
        # 生成综合策略建议
        strategy = self._compile_strategy(signals, 'medium')
        return strategy
    
    def generate_long_term_strategy(self, stock_code, fundamental_analysis):
        """生成长期策略（6个月以上）"""
        signals = []
        
        # 主要基于基本面分析
        if fundamental_analysis['pe_ratio'] < fundamental_analysis['industry_avg_pe'] * 0.8:
            signals.append({
                'signal': 'buy',
                'strength': 'strong',
                'reason': 'PE率显著低于行业平均',
                'timeframe': 'long'
            })
        
        if fundamental_analysis['dividend_yield'] > 4.0:
            signals.append({
                'signal': 'buy',
                'strength': 'strong',
                'reason': '高股息率股票，适合长期持有',
                'timeframe': 'long'
            })
            
        # 生成综合策略建议
        strategy = self._compile_strategy(signals, 'long')
        return strategy
    
    def _compile_strategy(self, signals, timeframe):
        """综合多个信号生成最终策略"""
        if not signals:
            return {
                'action': 'hold',
                'confidence': 'low',
                'reasoning': '无明确信号，建议观望',
                'timeframe': timeframe
            }
        
        # 计算买入卖出信号数量及强度
        buy_count = sum(1 for s in signals if s['signal'] == 'buy')
        sell_count = sum(1 for s in signals if s['signal'] == 'sell')
        
        buy_strength = sum(
            1.0 if s['strength'] == 'strong' else 0.5
            for s in signals if s['signal'] == 'buy'
        )
        
        sell_strength = sum(
            1.0 if s['strength'] == 'strong' else 0.5
            for s in signals if s['signal'] == 'sell'
        )
        
        # 决定最终行动
        if buy_strength > sell_strength:
            action = 'buy'
            strength = buy_strength
            reasons = [s['reason'] for s in signals if s['signal'] == 'buy']
        elif sell_strength > buy_strength:
            action = 'sell'
            strength = sell_strength
            reasons = [s['reason'] for s in signals if s['signal'] == 'sell']
        else:
            action = 'hold'
            strength = 0
            reasons = ['买卖信号强度相当，建议观望']
        
        # 计算置信度
        if strength >= 2:
            confidence = 'high'
        elif strength >= 1:
            confidence = 'medium'
        else:
            confidence = 'low'
            
        return {
            'action': action,
            'confidence': confidence,
            'reasoning': '; '.join(reasons),
            'timeframe': timeframe
        } 